package org.bdware.irp.irpserver;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class IrpServerImpl implements IrpServer{
    static Logger logger = Logger.getLogger(NettyIrpListener.class);
    List<IrpListener> listeners;
    IrpServerInfo serverInfo;

    List<ListenerContainer> containers;
    IrpRequestHandler requestCallback;

    public IrpServerImpl(IrpServerInfo info){
        this.serverInfo = info;
        listeners = new ArrayList<>();
        for (IrpListenerInfo listenerInfo:info.listenerInfos){
            IrpListener listener = NettyIrpListener.CreateIrpListener(listenerInfo);
            listeners.add(listener);
        }
        containers = new ArrayList<>();
    }

    public static IrpServer createIrpServer(IrpServerInfo info){
        return new IrpServerImpl(info);
    }

    @Override
    public void start(){
        logger.info("IRPServerInfo: " + serverInfo.toJson());
        for(IrpListener listener:listeners){
            listener.setRequestHandler(requestCallback);
            ListenerContainer container = new ListenerContainer(listener);
            containers.add(container);
            container.start();
        }
    }

    @Override
    public void stop(){
        logger.info("Try to stop listeners:");
        for(IrpListener listener:listeners){
            listener.stop();
        }
        for(ListenerContainer c: containers){
            c.interrupt();
        }
    }

    @Override
    public void setIrsServerHandler(IrsHandler handler) {
        requestCallback = new IrpRequestHandlerImpl(handler);
    }

    @Override
    public void setGrsServerHandler(GrsHandler handler) {
        requestCallback = new IrpRequestHandlerImpl(handler);
    }

    public class ListenerContainer extends Thread{
        IrpListener listener;
        ListenerContainer(IrpListener l){
            this.listener = l;
        }
        @Override
        public void run(){
            listener.start();
        }
    }
}
